package com.ruoyi.framework.shiro.realm;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.shiro.service.SysLoginService;
import com.ruoyi.framework.shiro.token.JwtToken;
import com.ruoyi.framework.shiro.token.JwtUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class JwtRealm extends AuthorizingRealm {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ISysUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwt = (String) token.getPrincipal();
        if (!jwtUtils.validateToken(jwt)) {
            throw new AuthenticationException("token无效");
        }
        String userId = jwtUtils.getUsernameFromToken(jwt);
        // SysUser user = userService.selectUserById(Long.valueOf(userId));
        // 只设置了userId
        SysUser user = new SysUser();
        user.setUserId(Long.valueOf(userId));
        return new SimpleAuthenticationInfo(user, jwt, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 权限验证逻辑
        return null;
    }
}
